﻿$d = {
    string: {
        truncate: function (string, length, ellipse) {
            ellipse = ellipse || "...";
            length |= 0;
            if (string && length > 0 && string.length > length)
                return string.substring(0, length) + ellipse;
            else
                return string;
        },

        stripHTML: function (string) {
            return $('<div/>').html(string).text();
        },

        encodeHTML: function (string) {
            return $('<div/>').text(string).html();
        },

        decodeHTML: function (string) {
            return $('<textarea/>').html(string).text();
        }
    },

    datetime: {
        parse: function (value, format) {
            if (value == null)
                return null;
            if (typeof value == "string") {
                if (value.length > 6 && value.substring(0, 6) == "/Date(")
                    value = new Date(parseInt(value.substr(6)))
                else {
                    value = format ? Date.parseExact(value, format) : Date.parse(value);
                }
            }

            return value;
        },

        format: function (value, toFormat, fromFormat) {
            value = this.parse(value, fromFormat);
            return value == null ? "" : value.toString(toFormat || "yyyy-MM-dd HH:mm:ss");
        },

        validate: function (value, format) {
            if (value == null || value == "")
                return true;
            else
                return this.parse(value, format) != null;
        }
    },

    guid: {
        generate: function () {
            var S4 = function () {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            };
            return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
        },
        validate: function (value) {
            var validGuid = /^({|()?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}(}|))?$/;
            var emptyGuid = /^({|()?0{8}-(0{4}-){3}0{12}(}|))?$/;
            return validGuid.test(value) && !emptyGuid.test(value);
        }
    },

    url: {
        para: function (name) {
            return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ''])[1]);
        }
    }
};
   